﻿using NationalInstruments.DAQmx;
using Newtonsoft.Json;
using ScottPlot;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Controls;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Enums;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Models;

namespace 低频天线阵列相控阵信号发生系统SmartFASK12.View
{
    public partial class USmartFASK12 : UserControl
    {
        private List<SmartFASK12Model> _smartFASK12Models;
        /// <summary>
        /// SmartFASK12参数集合
        /// </summary>
        private List<SmartFASK12Model> smartFASK12Models 
        {
            get
            {
                if (_smartFASK12Models == null && File.Exists(MPublic.SmartFASK12FilePath))
                {
                    string txt = File.ReadAllText(MPublic.SmartFASK12FilePath);
                    _smartFASK12Models = JsonConvert.DeserializeObject<List<SmartFASK12Model>>(txt);
                }
                return _smartFASK12Models;
            }
            set
            {
                _smartFASK12Models = value;

                // 保存文件
                string json = JsonConvert.SerializeObject(_smartFASK12Models, Formatting.Indented);
                File.WriteAllText(MPublic.SmartFASK12FilePath, json);
            }
        }

        /// <summary>
        /// 信号类型
        /// </summary>
        private int _signalType_modulate = 1;
        public int SignalTypeModulate
        {
            get => _signalType_modulate;
            set
            {
                _signalType_modulate = value;
                if (_signalType_modulate == 0)
                {
                    button_random.BackColor = Color.White;
                    button_01.BackColor = Color.White;
                    button_10.BackColor = Color.Lime;
                    btn_ManualInput.BackColor = Color.White;
                }
                else if (_signalType_modulate == 1)
                {
                    button_random.BackColor = Color.White;
                    button_01.BackColor = Color.Lime;
                    button_10.BackColor = Color.White;
                    btn_ManualInput.BackColor = Color.White;
                }
                else if (_signalType_modulate == 2)
                {
                    button_random.BackColor = Color.Lime;
                    button_01.BackColor = Color.White;
                    button_10.BackColor = Color.White;
                    btn_ManualInput.BackColor = Color.White;
                }
                else if (_signalType_modulate == 3)
                {
                    button_random.BackColor = Color.White;
                    button_01.BackColor = Color.White;
                    button_10.BackColor = Color.White;
                    btn_ManualInput.BackColor = Color.Lime;
                }
            }
        }

        /// <summary>
        /// 输出电压
        /// </summary>
        private List<CalSingalInfo> _calSingalInfos = null;

        public USmartFASK12()
        {
            InitializeComponent();

            Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            dataGridView_wltdList.RowHeadersVisible = false;
            dataGridView_wltdList.AllowUserToAddRows = false;
            dataGridView_wltdList.AutoGenerateColumns = false;

            #region 禁止更改宽高 //---------------------------------
            // 禁止用户改变DataGridView的所有列的列宽   
            dataGridView_wltdList.AllowUserToResizeColumns = false;
            //禁止用户改变DataGridView所有行的行高   
            dataGridView_wltdList.AllowUserToResizeRows = false;
            // 禁止用户改变列头的高度   
            dataGridView_wltdList.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            // 禁止用户改变列头的宽度   
            dataGridView_wltdList.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            #endregion 

            // 获取物理通道
            string[] wltds = MNI.Singleton().GetChannals(PhysicalChannelTypes.AO);

            // 添加物理通道
            comboBox_wltd.Items.AddRange(wltds);
            if (comboBox_wltd.Items.Count > 0)
                comboBox_wltd.SelectedIndex = 0;

            // 赋值
            if (smartFASK12Models != null)
            {
                if (smartFASK12Models.Count > 0)
                {
                    int wltdIndex = Array.IndexOf(wltds, smartFASK12Models[0].physicalChannel);
                    comboBox_wltd.SelectedIndex = wltdIndex;

                    // 刷新物理通道集合
                    dataGridView_wltdList.DataSource = new BindingSource(new BindingList<SmartFASK12Model>(smartFASK12Models), null);

                    // 选中后赋值
                    AssignValueAfterSelection(0);
                }
            }
            else
            {
                smartFASK12Models = new List<SmartFASK12Model>();
            }
        }

        #region 操作数据

        /// <summary>
        /// 添加物理通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_addwltd_Click(object sender, EventArgs e)
        {
            // 物理通道
            string wltd = comboBox_wltd.Text;

            // 判断当前物理通道是否添加
            if (smartFASK12Models.Where(w => w.physicalChannel == wltd).Count() > 0)
            {
                MessageBox.Show("当前物理通道已存在！", "提示");
                return;
            }

            // 添加SmartFASK12数据
            smartFASK12Models.Add(new SmartFASK12Model()
            {
                isStart = false,
                physicalChannel = wltd,
                dutyCycle = (double)numericUpDown_DutyCycle.Value / 100,
                modulationMode = comboBox_CommissioningmodedemoModulation.SelectedIndex,
                signalfrequency_modulate = textBox_signalfrequency_modulate.Text,
                samplingrate_modulate = textBox_samplingrate_modulate.Text,
                carrierfrequency1_modulate = textBox_Carrierfrequency1_modulate.Text,
                carrierfrequency2_modulate = textBox_Carrierfrequency2_modulate.Text,
                amplitude1_modulate = textBox_Amplitude1_modulate.Text,
                amplitude2_modulate = textBox_Amplitude2_modulate.Text,
                signalnumber = textBox_Showpoints_modulate.Text,
                standard1_modulate = textBox_standard1_modulate.Text,
                standard2_modulate = textBox_standard2_modulate.Text,
                phase1 = (double)numericUpDown_phase1.Value,
                phase2 = (double)numericUpDown_phase2.Value,
                signalsequence = richTextBox_signalsequence.Text,
                minValue = Convert.ToDouble(minimumNumeric.Value),
                maxValue = Convert.ToDouble(maximumNumeric.Value),
                signalType_modulate = SignalTypeModulate,
            });

            // 添加
            smartFASK12Models = smartFASK12Models;

            // 刷新物理通道集合
            dataGridView_wltdList.DataSource = new BindingSource(new BindingList<SmartFASK12Model>(smartFASK12Models), null);

            MessageBox.Show("添加参数成功！", "提示");
        }

        /// <summary>
        /// 删除物理通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_delete_wltd_Click(object sender, EventArgs e)
        {
            // 弹出一个确认删除的对话框  
            DialogResult result = MessageBox.Show("确定要删除这条数据吗?", "删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                int rowIndex = this.dataGridView_wltdList.CurrentRow.Index;

                if (rowIndex < 0)
                    return;

                // 移除
                smartFASK12Models.RemoveAt(rowIndex);

                // 保存
                smartFASK12Models = smartFASK12Models;

                // 刷新物理通道集合
                dataGridView_wltdList.DataSource = new BindingSource(new BindingList<SmartFASK12Model>(smartFASK12Models), null);

                //MessageBox.Show("参数保存成功！", "提示");
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_Click(object sender, EventArgs e)
        {
            // 选中行
            int rowIndex = this.dataGridView_wltdList.CurrentRow.Index;

            if (rowIndex < 0)
                return;

            // 修改
            smartFASK12Models[rowIndex] = new SmartFASK12Model()
            {
                isStart = smartFASK12Models[rowIndex].isStart,
                physicalChannel = smartFASK12Models[rowIndex].physicalChannel,
                dutyCycle = (double)numericUpDown_DutyCycle.Value / 100,
                modulationMode = comboBox_CommissioningmodedemoModulation.SelectedIndex,
                signalfrequency_modulate = textBox_signalfrequency_modulate.Text,
                samplingrate_modulate = textBox_samplingrate_modulate.Text,
                carrierfrequency1_modulate = textBox_Carrierfrequency1_modulate.Text,
                carrierfrequency2_modulate = textBox_Carrierfrequency2_modulate.Text,
                amplitude1_modulate = textBox_Amplitude1_modulate.Text,
                amplitude2_modulate = textBox_Amplitude2_modulate.Text,
                signalnumber = textBox_Showpoints_modulate.Text,
                standard1_modulate = textBox_standard1_modulate.Text,
                standard2_modulate = textBox_standard2_modulate.Text,
                phase1 = (double)numericUpDown_phase1.Value,
                phase2 = (double)numericUpDown_phase2.Value,
                signalsequence = richTextBox_signalsequence.Text,
                minValue = Convert.ToDouble(minimumNumeric.Value),
                maxValue = Convert.ToDouble(maximumNumeric.Value),
                signalType_modulate = SignalTypeModulate,
            };

            // 保存
            smartFASK12Models = smartFASK12Models;

            MessageBox.Show("参数保存成功！", "提示");
        }

        #endregion

        #region 数据生成类型

        /// <summary>
        /// 随机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_random_Click(object sender, EventArgs e)
        {
            SignalTypeModulate = (int)DataGenerationEnum.随机;
        }

        /// <summary>
        /// 01
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_01_Click(object sender, EventArgs e)
        {
            SignalTypeModulate = (int)DataGenerationEnum.生成01;
        }

        /// <summary>
        /// 手动输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ManualInput_Click(object sender, EventArgs e)
        {
            SignalTypeModulate = (int)DataGenerationEnum.手动输入;
        }

        /// <summary>
        /// 10
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_10_Click(object sender, EventArgs e)
        {
            SignalTypeModulate = (int)DataGenerationEnum.生成10;
        }

        #endregion

        #region 操作

        /// <summary>
        /// 发送一次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendOnce_Click(object sender, EventArgs e)
        {
            OutputVoltage(SampleQuantityMode.FiniteSamples);
        }

        /// <summary>
        /// 持续发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ContinuousLaunch_Click(object sender, EventArgs e)
        {
            OutputVoltage(SampleQuantityMode.ContinuousSamples);
        }

        /// <summary>
        /// 停止发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            MNI2.Singleton().Stop();
        }

        /// <summary>
        /// 输出电压
        /// </summary>
        /// <param name="sampleQuantityMode"></param>
        private void OutputVoltage(SampleQuantityMode sampleQuantityMode)
        {
            // 初始化
            _calSingalInfos = new List<CalSingalInfo>();
            // 查询启动的物理通道
            List<SmartFASK12Model> smartFASK12s = smartFASK12Models.Where(w => w.isStart == true).ToList();
            // 物理通道
            string physicalChannel = null;
            // 获取最大的信号数量
            int max_signalnumber = smartFASK12s.Select(s => MConvert.Singleton().KToInt(s.signalnumber)).Max();
            // 数据
            double[,] data = new double[smartFASK12s.Count, max_signalnumber];
            // 索引
            int smartFASK12s_Index = 0;
            // 最大值
            double maxValue = smartFASK12s.Select(s => s.maxValue).Max();
            // 最小值
            double minValue = smartFASK12s.Select(s => s.minValue).Min();
            // 采样率（第一个）
            double sampleClockRate_theFirst = MConvert.Singleton().KToDouble(smartFASK12s[0].samplingrate_modulate);
            // 信号个数（第一个）
            int signalnumber_theFirst = MConvert.Singleton().KToInt(smartFASK12s[0].signalnumber);
            // 赋值
            foreach (SmartFASK12Model smartFASK12 in smartFASK12s)
            {
                // 物理通道计算
                if (physicalChannel == null)
                    physicalChannel += smartFASK12.physicalChannel;
                else
                    physicalChannel += "," + smartFASK12.physicalChannel;

                #region 生成数据

                // 信号频率
                int signalfrequency_modulate = MConvert.Singleton().KToInt(smartFASK12.signalfrequency_modulate);
                // 采样率
                int samplingrate_modulate = MConvert.Singleton().KToInt(smartFASK12.samplingrate_modulate);
                // 载波频率1
                int carrierfrequency1_modulate = MConvert.Singleton().KToInt(smartFASK12.carrierfrequency1_modulate);
                // 载波频率2
                int carrierfrequency2_modulate = MConvert.Singleton().KToInt(smartFASK12.carrierfrequency2_modulate);
                // 幅度1/V：
                double amplitude1_modulate = MConvert.Singleton().KToDouble(smartFASK12.amplitude1_modulate);
                // 幅度2/V：
                double amplitude2_modulate = MConvert.Singleton().KToDouble(smartFASK12.amplitude2_modulate);
                // 基准1:
                double standard1_modulate = MConvert.Singleton().KToDouble(smartFASK12.standard1_modulate);
                // 基准2:
                double standard2_modulate = MConvert.Singleton().KToDouble(smartFASK12.standard2_modulate);
                // 占空比
                double dutyCycle = smartFASK12.dutyCycle;
                // 信号个数
                int signalnumber = MConvert.Singleton().KToInt(smartFASK12.signalnumber);
                // 信号类型
                int signalType_modulate = smartFASK12.signalType_modulate;
                // 手动输入的0101
                string signalsequence = smartFASK12.signalsequence;
                if (smartFASK12.modulationMode == (int)AFSKEnum.ASK)
                {
                    // 获取信号
                    CalSingalInfo _calSingalInfo = MJietiao.Singleton().CalSingalASK(signalfrequency_modulate,
                                                                                     samplingrate_modulate,
                                                                                     carrierfrequency1_modulate,
                                                                                     amplitude1_modulate,
                                                                                     standard1_modulate,
                                                                                     dutyCycle,
                                                                                     signalnumber,
                                                                                     signalType_modulate,
                                                                                     signalsequence);

                    // 添加
                    int resIndex = 0;
                    foreach (double res in _calSingalInfo.res)
                    {
                        // 添加数据
                        data[smartFASK12s_Index, resIndex] = res;
                        resIndex++;
                    }
                    _calSingalInfos.Add(_calSingalInfo);
                }

                else if (smartFASK12.modulationMode == (int)AFSKEnum.FSK)
                {
                    //生成电压
                    CalSingalInfo _calSingalInfo = MJietiao.Singleton().CalSingal2(signalfrequency_modulate,
                                                                                   signalnumber,
                                                                                   carrierfrequency1_modulate,
                                                                                   amplitude1_modulate,
                                                                                   standard1_modulate,
                                                                                   carrierfrequency2_modulate,
                                                                                   amplitude2_modulate,
                                                                                   standard2_modulate,
                                                                                   signalType_modulate,
                                                                                   signalsequence);
                    // 添加
                    int resIndex = 0;
                    foreach (double res in _calSingalInfo.res)
                    {
                        // 添加数据
                        data[smartFASK12s_Index, resIndex] = res;
                        resIndex++;
                    }
                    _calSingalInfos.Add(_calSingalInfo);
                }

                #endregion

                smartFASK12s_Index++;
            }

            // 发送电压
            bool isStart = MNI2.Singleton().OutputOoltage(physicalChannel, data, maxValue, minValue, sampleClockRate_theFirst, signalnumber_theFirst, sampleQuantityMode);

            if (!isStart)
            {
                MessageBox.Show("输出电压失败！", "错误");
                return;
            }

            #region 显示曲线图

            formsPlot.Plot.Clear();
            int _calSingalInfosIndex = 0;
            foreach (CalSingalInfo calSingal in _calSingalInfos)
            {
                //List<double> xs = new List<double>();
                //for (int i = 0; i < calSingal.res.Count; i++)
                //{
                //    xs.Add(i);
                //}
                formsPlot.Plot.AddSignal(calSingal.res.ToArray(), 
                                         1,
                                         MPublic.Colors[_calSingalInfosIndex],
                                         smartFASK12s[_calSingalInfosIndex].physicalChannel);

                //formsPlot.Plot.AddSignalXY(xs.ToArray(), calSingal.res.ToArray(), MPublic.Colors[_calSingalInfosIndex], smartFASK12s[_calSingalInfosIndex].physicalChannel);
                _calSingalInfosIndex++;
            }
            formsPlot.Plot.Legend();
            formsPlot.Plot.AxisAuto();
            formsPlot.Refresh();

            #endregion
        }

        #endregion

        /// <summary>
        /// 选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_wltdList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if (e.ColumnIndex == 0)
            {
                // The checkbox column was clicked.  
                // You can retrieve the checked state of the cell here.  
                if (dataGridView_wltdList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue != null)
                {
                    bool isChecked = (bool)dataGridView_wltdList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;

                    // 修改
                    smartFASK12Models[e.RowIndex].isStart = !isChecked;

                    // 保存
                    smartFASK12Models = smartFASK12Models;
                }
            }

            // 选中后赋值
            AssignValueAfterSelection(e.RowIndex);
        }

        /// <summary>
        /// 选中后赋值
        /// </summary>
        /// <param name="rowIndex"></param>
        private void AssignValueAfterSelection(int rowIndex)
        {
            SmartFASK12Model smartFASK12 = smartFASK12Models[rowIndex];
            comboBox_CommissioningmodedemoModulation.SelectedIndex = smartFASK12.modulationMode;
            textBox_signalfrequency_modulate.Text = smartFASK12.signalfrequency_modulate;
            textBox_samplingrate_modulate.Text = smartFASK12.samplingrate_modulate;
            textBox_Carrierfrequency1_modulate.Text = smartFASK12.carrierfrequency1_modulate;
            textBox_Carrierfrequency2_modulate.Text = smartFASK12.carrierfrequency2_modulate;
            textBox_Amplitude1_modulate.Text = smartFASK12.amplitude1_modulate;
            textBox_Amplitude2_modulate.Text = smartFASK12.amplitude2_modulate;
            textBox_Showpoints_modulate.Text = smartFASK12.signalnumber;
            textBox_standard1_modulate.Text = smartFASK12.standard1_modulate;
            textBox_standard2_modulate.Text = smartFASK12.standard2_modulate;
            SignalTypeModulate = smartFASK12.signalType_modulate;
            //相位
            numericUpDown_phase1.Value = (decimal)smartFASK12.phase1;
            numericUpDown_phase2.Value = (decimal)smartFASK12.phase2;
            //占空比
            numericUpDown_DutyCycle.Value = (decimal)smartFASK12.dutyCycle * 100;
            minimumNumeric.Value = (decimal)smartFASK12.minValue;
            maximumNumeric.Value = (decimal)smartFASK12.maxValue;
        }
    }
}
